<template>

</template>

<script setup>
import { ref, onMounted, onUnmounted,defineEmits  } from 'vue';
import { ElNotification } from 'element-plus'
import { getExamine } from '@/utils/jia-axios'
const emit = defineEmits(['updateParent']);
    const ws = ref(null);           // WebSocket 实例
    const receivedMessage = ref(''); // 存储接收到的消息

    // 初始化 WebSocket
    const initWebSocket = () => {
      ws.value = new WebSocket('ws://localhost:3300'); // WebSocket 地址

      ws.value.onopen = () => {
        console.log('WebSocket 连接已建立');
      };

      // 接收到消息时更新 receivedMessage
      ws.value.onmessage = (event) => {

        console.log('接收到的消息:', event.data);
        // receivedMessage.value = JSON.parse(event.data); // 更新 UI
        // 如果收到的是 Blob 数据
        if (event.data instanceof Blob) {
          const reader = new FileReader();

          reader.onload = function () {
            try {
              const message = JSON.parse(reader.result);
              console.log('解析后的消息:', message);
              receivedMessage.value = message; // 更新 UI
              ElNotification(message)
              getExamine().then((res) => {
                emit('updateParent', res.data.infoCount);
              })
            } catch (error) {
              console.error('无法解析 Blob 为 JSON:', error);
            }
          };
          reader.readAsText(event.data); // 将 Blob 转换为文本
        }
      };

      ws.value.onclose = () => {
        console.log('WebSocket 连接已关闭');
      };

      ws.value.onerror = (error) => {
        console.error('WebSocket 错误:', error);
      };
    };

    // 发送消息到 WebSocket 服务器
    const sendMessage = () => {
      if (ws.value && ws.value.readyState === WebSocket.OPEN) {
        const message = JSON.stringify({
          type: 'message1',
          message: 'Hello from Vue3!'
        })
        ws.value.send(message);
        console.log('已发送消息:', message);
      } else {
        console.error('WebSocket 未连接');
      }
    };

    // 初始化 WebSocket 连接
    onMounted(() => {
      initWebSocket();
    });

    // 组件卸载时关闭 WebSocket 连接
    onUnmounted(() => {
      if (ws.value) {
        ws.value.close();
      }
    });
</script>

<style scoped>
/* 样式 */
</style>
